<template>
  <div class="custom-tree-container">
    <el-tree
      style="max-width: 600px"
      :data="dataSource"
      node-key="id"
      :default-expand-all="false"
      :highlight-current="true"
      :props="defaultProps"
      @node-click="getFileContentById"
    >
      <template #default="{ node, data }">
        <div class="custom-tree-node">
          <span>{{ node.label }}</span>
          <div>
            <el-button v-if="data.isFile !== '1'" type="primary" link @click="appendDir(data)">
              新增文件夹
            </el-button>
            <el-button v-if="data.isFile !== '1'" type="primary" link @click="appendFile(data)">
              新增文件
            </el-button>
            <el-popconfirm :title="data.isFile === '1' ? '是否删除该文件?' : '是否删除该文件夹?'"
                           @confirm="remove(node, data)">
              <template #reference>
                <el-button
                  style="margin-left: 4px"
                  type="danger"
                  link
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </div>
        </div>
      </template>
    </el-tree>
  </div>
  <el-dialog v-model="dialogFormVisible" :title="dirOrFileCreateTitle" width="500">
    <el-form :model="form">
      <el-form-item label="名称" :label-width="formLabelWidth">
        <el-input v-model="form.customName" autocomplete="off"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addNode">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  <br>
  <el-button type="primary" @click="saveTemplateFile">
    保存模板文件
  </el-button>
  <el-button plain type="primary" @click="back2file">
    返回文件列表
  </el-button>
  <br>
  <br>
  <span>当前正在编辑 【{{ editor.title }}】 模板文件: </span>
  <br>
  <br>
<!--  <tiptap v-model="editor.content" />-->
  <el-input
    v-model="editor.content"
    style="width: 1000px"
    :rows="12"
    type="textarea"
    placeholder="请输入模板文件的内容..."
  />
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import type {RenderContentContext} from 'element-plus'
import {ElButton} from 'element-plus'
import {useRoute, useRouter} from "vue-router";
import {instance} from '@/api/base'

const editor = reactive({
  title: '',
  content: '',
})

const route = useRoute()
const router = useRouter()
const groupData = ref({})

interface Tree {
  id: number
  label: string
  children?: Tree[]
  parent: string
  isFile: string
  content: string
}

const dialogFormVisible = ref(false)
const formLabelWidth = ref('140px')
const dirOrFileCreateTitle = ref('')
const addData = ref<Tree>()
const form = reactive({
  pkid: '',
  customName: '',
})

type Node = RenderContentContext['node']
type Data = RenderContentContext['data']

const defaultProps = {
  children: 'children',
  label: 'label',
  disabled: (one) => {
    return one.isFile !== '1'
  },
}

const addNode = () => {
  const newChild = {
    id: addData.value.parent ? addData.value.parent : ''  + '/' + addData.value.label + '/' + form.customName,
    parent: addData.value.parent ? addData.value.parent : ''  + '/' + addData.value.label,
    label: form.customName,
    children: [],
    isFile: dirOrFileCreateTitle.value === '创建目录' ? '0' : '1',
    newOne: '1',
  }
  if (!addData.value.children) {
    addData.value.children = []
  }
  addData.value.children.push(newChild)
  dataSource.value = [...dataSource.value]
  dialogFormVisible.value = false
}

const appendDir = (data: Data) => {
  addData.value = data
  dirOrFileCreateTitle.value = '创建目录'
  form.pkid = ''
  form.customName = ''
  dialogFormVisible.value = true
}

const appendFile = (data: Data) => {
  addData.value = data
  dirOrFileCreateTitle.value = '创建文件'
  form.pkid = ''
  form.customName = ''
  dialogFormVisible.value = true
}

const remove = (node: Node, data: Data) => {
  console.log('删除11111', data, node)
  // 手动递归找出所有的待删除的文件
  const deleteIdList = []
  const treeList = [data]
  while (treeList.length != 0) {
    let pop = treeList.pop();
    if (pop.children) {
      treeList.push(...pop.children)
    }
    if (pop.isFile === '1') {
      deleteIdList.push(pop.id)
    }
  }
  console.log('待删除的文件', deleteIdList)
  // 调用删除接口
  console.log('待删除的文件pkid为: ', deleteIdList.join(','))
  instance.post('/templateFileInfo/deleteTemplate?id=' + deleteIdList.join(',')).then((res) => {
    console.log(res)
    // listFileTreeByGroupId()
    const parent = node.parent
    const children: Tree[] = parent?.data.children || parent?.data
    const index = children.findIndex((d) => d.id === data.id)
    children.splice(index, 1)
    dataSource.value = [...dataSource.value]
  }).catch((err) => {
    console.log(err)
  })
}

const dataSource = ref<Tree[]>([])
const listFileTreeByGroupId = () => {
  instance.post('/templateFileInfo/listFileTreeByGroupId', {
    groupId: groupData.value,
  }).then((res) => {
    dataSource.value = [...res.data.data]
  }).catch((err) => {
    console.log(err)
  })
}

const currData = ref<Tree>()

const getFileContentById = (data, node, p3, p4) => {
  currData.value = data
  console.log('p1', data)
  console.log('p2', node)
  console.log('p3', p3)
  console.log('p4', p4)
  if (data.isFile === '1' && data.newOne !== '1') {
    // 刷新文本框的内容
    instance.post('/templateFileInfo/getFileContentById?id=' + data.id).then((res) => {
      console.log(res)
      editor.content = res.data.data.templateFileContent
      editor.title = res.data.data.templateFileName
      console.log(editor)
    }).catch((err) => {
      console.log(err)
    })
  } else {
    editor.content = currData.value.content ? currData.value.content : ''
    editor.title = data.label
  }
}

const saveTemplateFile = () => {
  instance.post('/templateFileInfo/saveTemplate', {
    pkid: currData.value.newOne === '1' ? '' : currData.value.id,
    groupId: groupData.value,
    templateFileName: currData.value.label,
    fileDirPath: currData.value.parent,
    templateFileContent: editor.content,
  }, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then((res) => {
    console.log(res)
    currData.value.content = editor.content
  }).catch((err) => {
    console.log(err)
  })
}

onMounted(() => {
  groupData.value = route.query.groupId
  // groupData.value = '1946857966263209984'
  if (!groupData.value) {
    router.push({name: 'modelList'})
  }
  console.log(groupData)
  listFileTreeByGroupId()
})

const back2file = () => {
  router.push({
    name: 'templateList',
    query: {
      groupId: groupData.value
    }
  })
}
</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
